﻿CREATE FUNCTION [Utilities].[ReadBit]
(
	-- the bits to check as an integer
	@iBits INT
	-- this bit to test
	-- this must be a bit value
	-- e.g. 1, 2, 4, 8, 16, 32, 64, etc
	-- non bit values will produce unknown results
	-- e.g. 3, 5, 6, 7, 9, 10, 11, etc
	,@iTestBit INT
)
RETURNS BIT
AS
BEGIN
	DECLARE @ComparisonResults INT;

	-- we are validating that the testbit paramater is a bit
	-- if it isn't, we return null
	IF (Utilities.IsBit(@iTestBit) = 0)
		RETURN NULL;

	-- bitwise and the bits and the test bit 
	SET @ComparisonResults = @iBits & @iTestBit;

	-- if the result equals the test bit, the bit is present
	IF (@ComparisonResults = @iTestBit)
		RETURN 1;
	ELSE
		RETURN 0;

	-- this return is required by the function
	-- it should never be hit
	RETURN 0;
END;